package com.woohua.thread.completefeature;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/***
 * @title ComplexTask
 * @description
 * @author woo hua
 * @version 1.0.0
 * @create 2023/3/21 10:41
 **/
public class ComplexTask {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 16. anyOf 返回优先执行完成的任务返回结果
        CompletableFuture future16 = CompletableFuture.anyOf(CompletableFuture.supplyAsync(() -> {
            sleep(300);
            System.out.println("16.1 TaskA be called.");
            return "16.2 TaskA return value.";
        }), CompletableFuture.supplyAsync(() -> {
            sleep(300);
            System.out.println("16.3 TaskB be called.");
            return "16.4 TaskB return value.";
        }));
        System.out.println("16.5 get: " + future16.get());
        sleep(400);

        // 17. allOf 所有结果执行完成，无返回值
        CompletableFuture<Void> future17 = CompletableFuture.allOf(CompletableFuture.supplyAsync(() -> {
            sleep(300);
            System.out.println("17.1 TaskA be called.");
            return "17.2 TaskA return value.";
        }), CompletableFuture.supplyAsync(() -> {
            sleep(300);
            System.out.println("17.3 TaskB be called.");
            return "17.4 TaskB return value.";
        }));
        System.out.println("17.5 get: " + future17.get());
        sleep(400);
    }

    private static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
